package com.javaeye.dengyin2000.gwtmodel.client.ui;

import com.google.gwt.user.client.ui.TextBox;
import com.javaeye.dengyin2000.gwtmodel.client.convert.IConverter;
import com.javaeye.dengyin2000.gwtmodel.client.model.IModel;

public class PopulateTextBox extends TextBox implements IPopulateWidget {
	
	private IModel model;
	
	private IConverter converter;
	
	public PopulateTextBox() {
		super();
	}

	public PopulateTextBox(IModel model){
		super();
		this.model = model;
		syncModelValue();
	}
	
	public PopulateTextBox(String name){
		super();
		setName(name);
	}
	
	public PopulateTextBox(String name, IModel model){
		super();
		this.model = model;
		syncModelValue();
	}

	private void syncModelValue() {
		if (model.getObject() != null){
			Object object = model.getObject();
			if (converter != null){
				setText((String)converter.convert(object, String.class));
			}else{
				setText(object.toString());
			}
		}
	}
	
	public IModel getModel() {
		return this.model;
	}

	public void populateModel() {
		if (converter != null){
			Object object = converter.convert(getText(), Object.class);
			model.setObject(object);
			return ;
		}
		model.setObject(getText());
	}

	public void setModel(IModel model) {
		this.model = model;
		syncModelValue();
	}

	public IConverter getConverter() {
		return converter;
	}

	public void setConverter(IConverter converter){
		this.converter  = converter;
	}
}
